package com.bsj.sipgateway.sip.transmit.request.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.def.dto.RedisDeviceInfo;
import com.bsj.power.common.def.entity.FaultLog;
import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.entity.log.VideoOpLog;
import com.bsj.power.common.def.enums.VideoOpTypeEnum;
import com.bsj.power.common.mapper.DeviceMapper;
import com.bsj.power.common.mapper.FaultLogMapper;
import com.bsj.power.common.mapper.VideoOpLogMapper;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.sipgateway.cache.DeviceCache;
import com.bsj.sipgateway.common.constant.Constants;
import com.bsj.sipgateway.config.SipConfig;
import com.bsj.sipgateway.sip.auth.DigestServerAuthenticationHelper;
import com.bsj.sipgateway.sip.auth.RegisterLogicHandler;
import com.bsj.sipgateway.sip.bean.WvpSipDate;
import com.bsj.sipgateway.sip.event.EventPublisher;
import com.bsj.sipgateway.sip.transmit.request.SIPRequestAbstractProcessor;
import gov.nist.javax.sip.RequestEventExt;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.header.Expires;
import gov.nist.javax.sip.header.SIPDateHeader;
import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import redis.clients.bsj.JedisClusterBSJ;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.header.*;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author bsj-chenjunkang
 * @Description:收到注册请求 处理
 * @date 2022/8/24
 */
@Slf4j
public class RegisterRequestProcessor extends SIPRequestAbstractProcessor {

    private SipConfig sipConfig;

    private RegisterLogicHandler handler;

    private EventPublisher publisher;

    private DeviceMapper deviceMapper;

    private JedisClusterBSJ jedisClusterBSJ;

    private VideoOpLogMapper videoOpLogMapper;

    private FaultLogMapper faultLogMapper;

    /**
     * 收到注册请求 处理
     *
     * @param evt
     */
    @Override
    public void process(RequestEvent evt) {
        try {
            Request request = evt.getRequest();
            Response response = null;
            boolean passwordCorrect = false;
            // 注册标志  0：未携带授权头或者密码错误  1：注册成功   2：注销成功
            int registerFlag = 0;
            Device device = null;
            AuthorizationHeader authorhead = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
            // 校验密码是否正确
            if (authorhead != null) {
                passwordCorrect = new DigestServerAuthenticationHelper().doAuthenticatePlainTextPassword(request,
                        sipConfig.getSipPassword());
            }
            if (!sipConfig.getNeedPassword()) {
                passwordCorrect = true;
            }

            // 未携带授权头或者密码错误 回复401
            if (authorhead == null || !passwordCorrect) {
                if (authorhead == null) {
                    log.info("未携带授权头 回复401");
                } else if (!passwordCorrect) {
//                    log.info("密码错误 回复401");
                }
                response = getMessageFactory().createResponse(Response.UNAUTHORIZED, request);
                new DigestServerAuthenticationHelper().generateChallenge(getHeaderFactory(), response, sipConfig.getSipDomain());
            }
            // 携带授权头并且密码正确
            else if (passwordCorrect) {
                response = getMessageFactory().createResponse(Response.OK, request);
                // 添加date头
                SIPDateHeader dateHeader = new SIPDateHeader();
                // 使用自己修改的
                WvpSipDate wvpSipDate = new WvpSipDate(Calendar.getInstance(Locale.ENGLISH).getTimeInMillis());
                dateHeader.setDate(wvpSipDate);
                response.addHeader(dateHeader);

                ExpiresHeader expiresHeader = (ExpiresHeader) request.getHeader(Expires.NAME);
                // 添加Contact头
                response.addHeader(request.getHeader(ContactHeader.NAME));
                // 添加Expires头
                response.addHeader(request.getExpires());

                // 1.获取到通信地址等信息，保存到deviceCache
                FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
                ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
                String received = viaHeader.getReceived();
                int rPort = viaHeader.getRPort();
                // 本地模拟设备 received 为空 rPort 为 -1
                // 解析本地地址替代
                if (StringUtils.isEmpty(received) || rPort == -1) {
                    received = viaHeader.getHost();
                    rPort = viaHeader.getPort();
                }
                //
                AddressImpl address = (AddressImpl) fromHeader.getAddress();
                SipUri uri = (SipUri) address.getURI();
                String deviceId = uri.getUser();
                // 设备注册成功初始化缓存信息
                device = new Device();
                device.setStreamMode("UDP");
                device.setDeviceId(deviceId);
                device.setIp(received);
                device.setPort(rPort);
//                device.setOnline(Constants.DEVICE_ONLINE);
                device.setRegisterTime(DateUtils.dateToStr(new Date()));
                // 注册时候默认国标通道号就是设备id，等到查询catalog消息时再更新设备通道id
                // 不再默认通道号就是设备id，这里会有问题，比如cvr，nvr上传的时候，真实通道跟设备id没有关系
                device.setChannelIdStr(deviceId);
                //获取外网的ip和端口
                RequestEventExt eventExt = (RequestEventExt) evt;
                String ipAddress = eventExt.getRemoteIpAddress();
                SIPRequest sipRequest = (SIPRequest) evt.getRequest();
                int port = sipRequest.getPeerPacketSourcePort();
                device.setHostAddress(ipAddress.concat(":").concat(String.valueOf(port)));
                // 注销成功
                if (expiresHeader != null && expiresHeader.getExpires() == 0) {
                    registerFlag = 2;
                }
                // 注册成功
                else {
                    registerFlag = 1;
                    // 判断TCP还是UDP
                    boolean isTcp = false;
                    ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
                    String transport = reqViaHeader.getTransport();
                    if (transport.equals("TCP")) {
                        isTcp = true;
                    }
                    device.setTransport(isTcp ? "TCP" : "UDP");
                }
            }
            //设置设备的外网端口
            setRport(evt, response);
            //响应设备
            getServerTransaction(evt).sendResponse(response);
            // 注册成功
            if (registerFlag == 1 && device != null) {
                // 是否是刷新注册的标识，海康设备每隔15分钟自动刷新注册一次，大华每隔54分钟刷新注册一次，如果是设备在线状态下，刷新注册不处理
                boolean updateRegisterFlag = true;
                String str = jedisClusterBSJ.get(RedisConstant.REDIS_DEVICE_INFO + device.getDeviceId());
                if (str == null || "".equals(str)) {
                    updateRegisterFlag = false;
                } else {
                    RedisDeviceInfo redisDeviceInfo = JSONObject.parseObject(str, RedisDeviceInfo.class);
                    if (redisDeviceInfo == null) {
                        updateRegisterFlag = false;
                    } else {
                        if (System.currentTimeMillis() - redisDeviceInfo.getKeepAliveTime() > 180000L) {
                            updateRegisterFlag = false;
                        } else {
                            log.info("设备刷新注册，据上次KeepAlive时间未超过3分钟，暂不处理，deviceId={}", device.getDeviceId());
                        }
                    }
                }
                if (updateRegisterFlag) {
                    return;
                }

                log.info("注册成功! deviceId:" + device.getDeviceId());
                device.setRegisterTime(DateUtils.dateToStr(new Date()));

                // 删除redis中直播通道的状态
                Long did = deviceMapper.selectIdByDeviceId(device.getDeviceId());
                if (did != null) {
                    jedisClusterBSJ.hdel(RedisConstant.VIDEO_PLAY_STATUS, did + "-1");
                    jedisClusterBSJ.hdel(RedisConstant.VIDEO_PLAY_STATUS, did + "-2");
                }

                publisher.onlineEventPublish(device, Constants.EVENT_ONLINE_REGISTER, null);
                //注册成功执行以下方法
                handler.onRegister(device, request.getExpires().getExpires());

                // 把设备上线记录到日志中
                try {
                    VideoOpLog videoOpLog = new VideoOpLog();
                    int type = VideoOpTypeEnum.DEVICE_LOGIN.getOpType();
                    videoOpLog.setDeviceId(device.getDeviceId());
                    videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                    videoOpLog.setOpUserId(2L);
                    videoOpLog.setOpUserName("admin");
                    videoOpLog.setOpType(type);
                    videoOpLog.setOpTime(new Date());
                    videoOpLog.setContent("设备上线：" + device.getDeviceId());
                    videoOpLog.setNickName(device.getNickName());
                    Device deviceByDeviceId = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
                    if (deviceByDeviceId != null) {
                        videoOpLog.setEquipmentNumber(deviceByDeviceId.getEquipmentNumber());
                    }
                    videoOpLogMapper.insert(videoOpLog);
                } catch (Exception e) {
                    log.error("记录设备上线日志失败：{}", ExceptionUtil.getStackStr(e));
                }

                // 判断如果上次是异常离线，记录异常离线时间
                VideoOpLog videoOpLog = videoOpLogMapper.selectBiggestCreateTimeOne(device.getDeviceId());
                if (videoOpLog != null && videoOpLog.getIntervalMillions() == 0) {
                    videoOpLog.setIntervalMillions(System.currentTimeMillis() - videoOpLog.getCreateTime().getTime());
                    videoOpLogMapper.updateById(videoOpLog);
                }

                // 如果redis中有需要写入faultLog的完结状态，写入到faultLog日志中
                String faultLogStr = jedisClusterBSJ.get(RedisConstant.FAULT_LOG_FINISH + device.getDeviceId());
                if (faultLogStr != null) {
                    FaultLog faultLog = JSON.parseObject(faultLogStr, FaultLog.class);
                    if (faultLog != null) {
                        faultLogMapper.insert(faultLog);
                        jedisClusterBSJ.del(RedisConstant.FAULT_LOG_FINISH + device.getDeviceId());
                    }
                }

            } else if (registerFlag == 2) {
                try {
                    VideoOpLog videoOpLog = new VideoOpLog();
                    int type = VideoOpTypeEnum.DEVICE_LOGOUT.getOpType();
                    videoOpLog.setDeviceId(device.getDeviceId());
                    videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                    videoOpLog.setOpUserId(2L);
                    videoOpLog.setOpUserName("admin");
                    videoOpLog.setOpType(type);
                    videoOpLog.setOpTime(new Date());
                    videoOpLog.setContent("设备离线：" + device.getDeviceId());
                    videoOpLog.setNickName(DeviceCache.getDevice(device.getDeviceId()).getNickName());
                    Device deviceByDeviceId = deviceMapper.getDeviceByDeviceId(device.getDeviceId());
                    if (deviceByDeviceId != null) {
                        videoOpLog.setEquipmentNumber(deviceByDeviceId.getEquipmentNumber());
                    }
                    videoOpLogMapper.insert(videoOpLog);
                } catch (Exception e) {
                    log.error("记录设备离线日志失败：{}", ExceptionUtil.getStackStr(e));
                }

                publisher.outlineEventPublish(device.getDeviceId(), Constants.EVENT_OUTLINE_UNREGISTER);
                log.info("注销成功! deviceId:" + device.getDeviceId());

            }
        } catch (SipException | InvalidArgumentException | NoSuchAlgorithmException | ParseException e) {
            log.error("处理设备注册注销请求异常", e);
        }
    }

    public void setSipConfig(SipConfig sipConfig) {
        this.sipConfig = sipConfig;
    }

    public void setHandler(RegisterLogicHandler handler) {
        this.handler = handler;
    }

    public void setPublisher(EventPublisher publisher) {
        this.publisher = publisher;
    }

    public void setDeviceMapper(DeviceMapper deviceMapper) {
        this.deviceMapper = deviceMapper;
    }

    public void setJedisClusterBSJ(JedisClusterBSJ jedisClusterBSJ) {
        this.jedisClusterBSJ = jedisClusterBSJ;
    }

    public void setVideoOpLogMapper(VideoOpLogMapper videoOpLogMapper) {
        this.videoOpLogMapper = videoOpLogMapper;
    }

    public void setFaultLogMapper(FaultLogMapper faultLogMapper) {
        this.faultLogMapper = faultLogMapper;
    }
}
